const app = getApp()
const api = require('../../utils/api.js')
const mockData = require('../../utils/data.js')

const USE_MOCK = false

function normalizeProduct(item = {}) {
  if (!item) {
    return null
  }

  const priceValue = item.marketPrice != null ? item.marketPrice : item.price
  const price = priceValue != null && priceValue !== ''
    ? Number(priceValue).toFixed(2)
    : '--'

  const originalPriceValue = item.originalPrice != null ? item.originalPrice : ''
  const onlineDateSource = item.onlineAt || item.earliestDate || ''
  const onlineDate = typeof onlineDateSource === 'string'
    ? onlineDateSource.split(' ')[0]
    : ''

  // 确保id字段正确映射（数据库返回的是productId，需要映射到id）
  const productId = item.productId != null ? item.productId : item.id

  return {
    id: productId,
    title: item.productName || item.title || '',
    location: item.city || item.destination || item.location || '',
    image: item.image || 'https://picsum.photos/seed/product/600/400',
    rating: item.rating != null ? Number(item.rating).toFixed(1) : '0.0',
    reviewCount: item.reviewCount != null ? item.reviewCount : 0,
    sales: item.salesCount != null ? item.salesCount : (item.sales != null ? item.sales : 0),
    price,
    originalPrice: originalPriceValue,
    earliestDate: onlineDate,
    productType: item.productType || 'normal',
    date: item.date || ''
  }
}

Page({
  data: {
    type: 'all', // all, flash-sale, group-buy, bargain, seasonal-hot
    city: '', // 城市筛选
    province: '', // 省份筛选
    title: '产品列表',
    products: [],
    loading: false
  },
  
  onLoad(options) {
    const type = options.type || 'all'
    const city = options.city ? decodeURIComponent(options.city) : ''
    const province = options.province ? decodeURIComponent(options.province) : ''
    let title = city || province || '产品列表'
    
    switch(type) {
      case 'flash-sale':
        title = '智云秒杀'
        break
      case 'group-buy':
        title = '拼团产品'
        break
      case 'bargain':
        title = '砍价产品'
        break
      case 'seasonal-hot':
        title = '当季热门'
        break
    }
    
    // 如果有城市或省份参数，标题显示
    if (city) {
      title = city + ' - ' + title
    } else if (province) {
      title = province + ' - ' + title
    }
    
    this.setData({
      type,
      city,
      province,
      title
    })
    
    wx.setNavigationBarTitle({
      title: city || province || title
    })
    
    this.loadProducts()
  },
  
  loadProducts() {
    this.setData({ loading: true })
    
    if (USE_MOCK) {
      // 本地数据模式
    setTimeout(() => {
        let products = (mockData.products || []).map(normalizeProduct).filter(Boolean)
        
        // 按城市筛选
        if (this.data.city) {
          products = products.filter(p => 
            p.location === this.data.city || 
            p.title.includes(this.data.city)
          )
        }
        
        // 按类型筛选
      if (this.data.type !== 'all') {
          products = products.filter(p => p.productType === this.data.type)
      }
      
      this.setData({
        products,
        loading: false
      })
      }, 300)
      return
    }
    
    // API模式：从数据库获取对应城市或省份的产品
    const params = { status: "3" } // 只获取已上线的产品（注意：status是字符串类型）
    if (this.data.city) {
      params.city = this.data.city
      console.log('查询城市:', this.data.city) // 添加日志
    }
    if (this.data.province) {
      params.province = this.data.province // 支持省份模糊查询
    }
    
    console.log('请求参数:', params) // 添加日志
    
    api.getProducts(params)
      .then(products => {
        console.log('获取到的产品数据:', products) // 添加日志
        const normalizedProducts = (products || []).map(normalizeProduct).filter(Boolean)
        console.log('标准化后的产品:', normalizedProducts) // 添加日志
        
        // 按类型筛选
        if (this.data.type !== 'all') {
          normalizedProducts = normalizedProducts.filter(p => p.productType === this.data.type)
        }
        
        this.setData({
          products: normalizedProducts,
          loading: false
        })
        
        if (normalizedProducts.length === 0) {
          wx.showToast({
            title: '暂无该城市的产品',
            icon: 'none',
            duration: 2000
          })
        }
      })
      .catch(err => {
        console.error('加载产品失败:', err)
        wx.showToast({
          title: '网络请求失败，使用本地数据',
          icon: 'none',
          duration: 2000
        })
        // 降级到本地数据
        let fallbackProducts = (mockData.products || []).map(normalizeProduct).filter(Boolean)
        if (this.data.city) {
          fallbackProducts = fallbackProducts.filter(p => 
            p.location === this.data.city || 
            p.title.includes(this.data.city)
          )
        }
        this.setData({
          products: fallbackProducts,
          loading: false
        })
      })
  },
  
  goToProductDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/product-detail/product-detail?id=${id}`
    })
  },
  
  onPullDownRefresh() {
    this.loadProducts()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  }
})

